package org.zj.webview.app.util;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author zj
 * @since 2025/8/23
 */
public class SqlInitUtils {
    private static final String SQL_FILE_PATH = "/sql/do/init.sql";

    private SqlInitUtils() {
    }

    /**
     * 初始化数据库
     *
     * @param dataSource
     * @return
     * @throws IOException
     * @throws SQLException
     */
    public static boolean initSql(DataSource dataSource) throws IOException, SQLException {
        try (Connection connection = dataSource.getConnection()) {
            boolean autoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            try (Statement statement = connection.createStatement()) {
                return statement.execute(getInitSql());
            } catch (SQLException e) {
                connection.rollback();
            } finally {
                connection.commit();
                connection.setAutoCommit(autoCommit);
            }
            return false;
        }
    }

    private static String getInitSql() throws IOException {
        try (InputStream inputStream = SqlInitUtils.class.getResourceAsStream(SQL_FILE_PATH)) {
            assert inputStream != null;
            byte[] bytes = inputStream.readAllBytes();
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }
}
